package com.wrox.todolist;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class TodoListActivity extends Activity 
	implements AddNewTodoItemListener, LoaderManager.LoaderCallbacks<Cursor> {

	private static final int CONTEXT_CANCEL = Menu.FIRST+1;
	private static final int CONTEXT_DELETE = Menu.FIRST+2;
	private static final int CONTEXT_FINISHED = Menu.FIRST+3;
	private static final int CONTEXT_DELETEALL = Menu.FIRST+4;
	
	private ArrayList<TodoItem> todoItems;
	private TodoItemArrayAdapter aa;
	private TodoListFragment fragmentTodoList;
	private NewItemFragment fragmentAddNew;
	private int selected_position = -1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_todo_list);
        
        todoItems = new ArrayList<TodoItem>();
        aa = new TodoItemArrayAdapter(this, R.layout.todo_item_view, todoItems);
        
        FragmentManager fm = this.getFragmentManager();
        fragmentTodoList = (TodoListFragment) fm.findFragmentById(R.id.fragment_todo_list);
        fragmentTodoList.setListAdapter(aa);
        ListView lv = fragmentTodoList.getListView();
        lv.setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				selected_position = position;
				return false;
			}        	
        });
        this.registerForContextMenu(lv);
        
        fragmentAddNew = (NewItemFragment) fm.findFragmentById(R.id.fragment_add_new);
        fragmentAddNew.setAddNewTodoItemListener(this);
        
        getLoaderManager().initLoader(0, null, this);
    }

    @Override
	protected void onResume() {
		super.onResume();
		getLoaderManager().restartLoader(0, null, this);
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_todo_list, menu);
        return true;
    }

	@Override
	public void addNew(String item) {
		//todoItems.add(0, new TodoItem(item));
		//aa.notifyDataSetChanged();
		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		values.put(TodoContentProvider.KEY_TASK, item);
		values.put(TodoContentProvider.KEY_CREATED, System.currentTimeMillis());
		values.put(TodoContentProvider.KEY_FINISHED, 0);
		cr.insert(TodoContentProvider.CONTENT_URI, values);
		getLoaderManager().restartLoader(0, null, this);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(Menu.NONE, CONTEXT_CANCEL, Menu.NONE, "CANCEL");
		
		if (selected_position >= 0) {
			menu.add(Menu.NONE, CONTEXT_DELETE, Menu.NONE, "Delete");
			menu.add(Menu.NONE, CONTEXT_FINISHED, Menu.NONE, 
					todoItems.get(selected_position).isFinished() ? "Mark as unfinished" : "Marked as finished");
		}
		menu.add(Menu.NONE, CONTEXT_DELETEALL, Menu.NONE, "DELETE ALL !!!");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CONTEXT_CANCEL:
			Toast.makeText(this, "Cancel", Toast.LENGTH_LONG).show();
			return true;
		case CONTEXT_DELETE:
			if (selected_position >= 0) {
//				todoItems.remove(selected_position);
//				aa.notifyDataSetChanged();
				ContentResolver cr = getContentResolver();
				Uri uri = Uri.parse(TodoContentProvider.CONTENT_URI+String.valueOf(todoItems.get(selected_position).getId()));
				cr.delete(uri, null, null);
				getLoaderManager().restartLoader(0, null, TodoListActivity.this);
			}
			return true;
		case CONTEXT_FINISHED:
			if (selected_position >= 0) {
//				todoItems.get(selected_position).setFinished(!todoItems.get(selected_position).isFinished());
//				aa.notifyDataSetChanged();
				ContentResolver cr = getContentResolver();
				Uri uri = Uri.parse(TodoContentProvider.CONTENT_URI+String.valueOf(todoItems.get(selected_position).getId()));
				ContentValues values = new ContentValues();
				values.put(TodoContentProvider.KEY_FINISHED, !todoItems.get(selected_position).isFinished() ? 1 : 0);
				cr.update(uri, values, null, null);
				getLoaderManager().restartLoader(0, null, this);
			}
			return true;
		case CONTEXT_DELETEALL:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			OnClickListener listener = new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_NEGATIVE:
						break;
					case DialogInterface.BUTTON_POSITIVE:
						//todoItems.clear();
						//aa.notifyDataSetChanged();
						ContentResolver cr = getContentResolver();
						cr.delete(TodoContentProvider.CONTENT_URI, null, null);
						getLoaderManager().restartLoader(0, null, TodoListActivity.this);
						break;
					}
				}
			};
			builder.setMessage("Are you sure ?")
				.setPositiveButton("Yes", listener)
				.setNegativeButton("No", listener).show();
			return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		CursorLoader loader = new CursorLoader(this, TodoContentProvider.CONTENT_URI, null, null, null, null);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		int keyIdIndex = cursor.getColumnIndexOrThrow(TodoContentProvider.KEY_ID);
		int keyTaskIndex = cursor.getColumnIndexOrThrow(TodoContentProvider.KEY_TASK);
		int keyCreatedIndex = cursor.getColumnIndexOrThrow(TodoContentProvider.KEY_CREATED);
		int keyFinishedIndex = cursor.getColumnIndexOrThrow(TodoContentProvider.KEY_FINISHED);		
		todoItems.clear();
		while (cursor.moveToNext()) {

			TodoItem item = new TodoItem(
					cursor.getInt(keyIdIndex),
					cursor.getString(keyTaskIndex), 
					new Date(cursor.getLong(keyCreatedIndex)), 
					cursor.getInt(keyFinishedIndex) != 0);
			todoItems.add(item);			
		}
		aa.notifyDataSetChanged();
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub
		
	}
    
    
}
